/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.unipampa.view;

import br.unipampa.dados.DBConection;
import br.unipampa.dados.DBUsuario;
import br.unipampa.utilitarios.ExecutaSom;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author Gabriel Moro
 */
public class PaneConfiguracao extends javax.swing.JPanel implements EfeitosSonoros {

    //MODELOS
    private DefaultTableModel modeloTableUser;
    private TableColumn modeloColunaI;
    private TableColumn modeloColunaII;
    private TableColumn modeloColunaIII;
    //OPERACOES
    private CadastroDeUsuarios cadastroUser;
    private EdicaoDeUsuarios edicaoUser;
    //BANCOS
    private DBConection conexao;
    private DBUsuario dbUser;
    //ATRIBUTOS
    public String nomeUsuario;

    /**
     * Creates new form PaneConfiguracao
     */
    public PaneConfiguracao() {
        initComponents();
        this.modeloTableUser = (DefaultTableModel) this.jTableUsuarios.getModel();
        jScrollPaneTabela.setVisible(false);
        this.jTableUsuarios.getTableHeader().setReorderingAllowed(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnListarUsuarios = new javax.swing.JButton();
        jPanelAcoes2 = new javax.swing.JPanel();
        btnNovoConf = new javax.swing.JButton();
        btnEditarConf = new javax.swing.JButton();
        btnExcluirConf = new javax.swing.JButton();
        jScrollPaneTabela = new javax.swing.JScrollPane();
        jTableUsuarios = new javax.swing.JTable();

        setBackground(new java.awt.Color(204, 204, 255));

        btnListarUsuarios.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unipampa/icons/updated.png.png"))); // NOI18N
        btnListarUsuarios.setToolTipText("Listar Usuários");
        btnListarUsuarios.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnListarUsuariosActionPerformed(evt);
            }
        });
        btnListarUsuarios.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnListarUsuariosKeyPressed(evt);
            }
        });

        jPanelAcoes2.setBackground(new java.awt.Color(204, 204, 204));
        jPanelAcoes2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Ações", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.ABOVE_TOP, null, new java.awt.Color(0, 0, 0)));

        btnNovoConf.setBackground(new java.awt.Color(153, 180, 209));
        btnNovoConf.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unipampa/icons/novo.png"))); // NOI18N
        btnNovoConf.setToolTipText("Cadastrar usuário");
        btnNovoConf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoConfActionPerformed(evt);
            }
        });

        btnEditarConf.setBackground(new java.awt.Color(153, 180, 209));
        btnEditarConf.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unipampa/icons/editar.png"))); // NOI18N
        btnEditarConf.setToolTipText("Editar usuário");
        btnEditarConf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarConfActionPerformed(evt);
            }
        });

        btnExcluirConf.setBackground(new java.awt.Color(153, 180, 209));
        btnExcluirConf.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unipampa/icons/lixeira.png"))); // NOI18N
        btnExcluirConf.setToolTipText("Excluir usuário");
        btnExcluirConf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirConfActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelAcoes2Layout = new javax.swing.GroupLayout(jPanelAcoes2);
        jPanelAcoes2.setLayout(jPanelAcoes2Layout);
        jPanelAcoes2Layout.setHorizontalGroup(
            jPanelAcoes2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelAcoes2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelAcoes2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnNovoConf, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnEditarConf, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnExcluirConf, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanelAcoes2Layout.setVerticalGroup(
            jPanelAcoes2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelAcoes2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnNovoConf, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEditarConf)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnExcluirConf)
                .addGap(6, 6, 6))
        );

        jTableUsuarios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Nome", "Senha", "Tipo de Usuário"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableUsuarios.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jTableUsuarios.getTableHeader().setResizingAllowed(false);
        jTableUsuarios.getTableHeader().setReorderingAllowed(false);
        jTableUsuarios.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTableUsuariosKeyPressed(evt);
            }
        });
        jScrollPaneTabela.setViewportView(jTableUsuarios);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanelAcoes2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(27, 27, 27)
                        .addComponent(jScrollPaneTabela, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnListarUsuarios, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnListarUsuarios, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanelAcoes2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(46, 46, 46)
                        .addComponent(jScrollPaneTabela, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(160, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnListarUsuariosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnListarUsuariosActionPerformed
        efeitoSonoro();
        evtListarUsuarios();
    }//GEN-LAST:event_btnListarUsuariosActionPerformed

    private void btnNovoConfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoConfActionPerformed
        efeitoSonoro();
        if (ApoioDeInterface.mensagemRealizarTarefa()) {
            this.cadastroUser = new CadastroDeUsuarios();
            this.cadastroUser.setVisible(true);
        }
    }//GEN-LAST:event_btnNovoConfActionPerformed

    private void btnEditarConfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarConfActionPerformed
        efeitoSonoro();
        editarUserEvt();
    }//GEN-LAST:event_btnEditarConfActionPerformed

    private void btnExcluirConfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirConfActionPerformed
        efeitoSonoro();
        excluirUserEvt();
    }//GEN-LAST:event_btnExcluirConfActionPerformed

    private void btnListarUsuariosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnListarUsuariosKeyPressed

        if (evt.getKeyCode() == evt.VK_F5) {
            evtListarUsuarios();
            efeitoSonoro();
        }
    }//GEN-LAST:event_btnListarUsuariosKeyPressed

    private void jTableUsuariosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableUsuariosKeyPressed

        if (evt.getKeyCode() == evt.VK_E) {
            efeitoSonoro();
            editarUserEvt();
        }
        if (evt.getKeyCode() == evt.VK_DELETE) {
            efeitoSonoro();
            excluirUserEvt();
        }
        if (evt.getKeyCode() == evt.VK_F5) {
            efeitoSonoro();
            evtListarUsuarios();
        }
    }//GEN-LAST:event_jTableUsuariosKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEditarConf;
    private javax.swing.JButton btnExcluirConf;
    private javax.swing.JButton btnListarUsuarios;
    private javax.swing.JButton btnNovoConf;
    private javax.swing.JPanel jPanelAcoes2;
    private javax.swing.JScrollPane jScrollPaneTabela;
    private javax.swing.JTable jTableUsuarios;
    // End of variables declaration//GEN-END:variables

    private void preencheTabelaUsuarios() {
        this.modeloTableUser.setNumRows(0);//limpa toda a tabela
        try {
            this.conexao = new DBConection();
            this.dbUser = new DBUsuario(this.conexao.getCon());
            ArrayList<Object> valores = this.dbUser.select("nome_usuarios,senha_usuarios,codigoTipoDeUser");

            for (int x = 0; x < valores.size(); x = x + 3) {
                this.modeloTableUser.addRow(new Object[]{
                    valores.get(x),
                    valores.get(x + 1),
                    valores.get(x + 2)});
            }
        } catch (SQLException erroSql) {
            ApoioDeInterface.mensagemErroBanco(erroSql.getMessage());
        } finally {
            this.conexao.encerrarConexao();
            this.dbUser.closedConnection();
            redimensionarColumnsComp();
        }
    }

    private void ativacaoDeButtonsConfiguracao(boolean ordem) {
        if (ordem) {
            this.btnNovoConf.setEnabled(true);
            this.btnEditarConf.setEnabled(true);
            this.btnExcluirConf.setEnabled(true);
        } else {
            this.btnNovoConf.setEnabled(false);
            this.btnEditarConf.setEnabled(false);
            this.btnExcluirConf.setEnabled(false);
        }
    }

    private void redimensionarColumnsComp() {
        this.jTableUsuarios.setAutoResizeMode(this.jTableUsuarios.AUTO_RESIZE_OFF);

        this.modeloColunaI = this.jTableUsuarios.getColumnModel().getColumn(0);
        this.modeloColunaI.setPreferredWidth(270);

        this.modeloColunaII = this.jTableUsuarios.getColumnModel().getColumn(1);
        this.modeloColunaII.setPreferredWidth(70);

        this.modeloColunaIII = this.jTableUsuarios.getColumnModel().getColumn(2);
        this.modeloColunaIII.setPreferredWidth(110);
    }

    /**
     * @return the jPanelAcoes2
     */
    public javax.swing.JPanel getjPanelAcoes2() {
        return jPanelAcoes2;
    }

    private void evtListarUsuarios() {
        ativacaoDeButtonsConfiguracao(true);
        preencheTabelaUsuarios();
        jScrollPaneTabela.setVisible(true);
        revalidate();
    }

    private void editarUserEvt() {
        try {
            if (ApoioDeInterface.mensagemRealizarTarefa()) {
                int numberLine = this.jTableUsuarios.getSelectedRow();
                //RECUPERA NOME DA TABELA DE USUÀRIOS
                Object x = this.modeloTableUser.getValueAt(numberLine, 0);
                String nome = String.valueOf(x);
                //RECUPERA O TIPO DE USUÀRIO DA TABELA DE USUÀRIOS
                Object x2 = this.modeloTableUser.getValueAt(numberLine, 2);
                String tipoDeUser = String.valueOf(x2);

                if (tipoDeUser.equalsIgnoreCase("Usuário Comum") || nome.equals(this.nomeUsuario)) {
                    this.conexao = new DBConection();
                    this.dbUser = new DBUsuario(this.conexao.getCon());
                    ArrayList<Object> dados = this.dbUser.selectEdicao(nome);
                    this.dbUser.closedConnection();
                    this.conexao.encerrarConexao();
                    this.edicaoUser = new EdicaoDeUsuarios(nome, dados.get(0).toString(), dados.get(1).toString(),
                            dados.get(2).toString(), dados.get(3).toString());

                    this.edicaoUser.setVisible(true);
                } else {
                    ApoioDeInterface.mensagemNaoEditaAdm();
                }
            }
        } catch (ArrayIndexOutOfBoundsException erro) {
            ApoioDeInterface.mensagemDeNaoSelecao();
        } catch (SQLException erro2) {
            ApoioDeInterface.mensagemErroBanco(erro2.getMessage());
        }
    }

    private void excluirUserEvt() {
        try {
            if (ApoioDeInterface.mensagemRealizarTarefa()) {

                int numberLine = this.jTableUsuarios.getSelectedRow();
                //RECUPERA O NOME DA TABELA DE USUÀRIOS
                Object x = this.modeloTableUser.getValueAt(numberLine, 0);
                String nome = String.valueOf(x);
                //RECUPERA O TIPO DE USUÀRIO DA TABELA DE USUÀRIOS
                Object x2 = this.modeloTableUser.getValueAt(numberLine, 2);
                String tipoDeUser = String.valueOf(x2);

                if (tipoDeUser.equalsIgnoreCase("Usuário Comum")) {
                    if (!nome.equalsIgnoreCase(this.nomeUsuario)) {
                        this.conexao = new DBConection();
                        this.dbUser = new DBUsuario(this.conexao.getCon());
                        this.dbUser.delete(nome);
                        ApoioDeInterface.mensagemDeDelete();
                        preencheTabelaUsuarios();
                        jScrollPaneTabela.setVisible(true);
                        revalidate();
                    } else {
                        ApoioDeInterface.mensagemDePerigoConf();
                    }
                } else {
                    ApoioDeInterface.mensagemNaoEditaAdm();
                }
            }
        } catch (SQLException erroSQL) {
            ApoioDeInterface.mensagemErroBanco(erroSQL.getMessage());
        } catch (ArrayIndexOutOfBoundsException erro) {
            ApoioDeInterface.mensagemDeNaoSelecao();
        }
    }

    @Override
    public void efeitoSonoro() {
        ExecutaSom exeSound = new ExecutaSom();
        exeSound.executar("/br/unipampa/sounds/click2.wav");
    }
}
